//
//  HHNetworking.m
//  HHNetworking
//
//  Created by lch on 2021/10/8.
//

#import "HHNetworking.h"
#import <AFNetworking/AFNetworking.h>
#import "MBProgressHUD+HHAdd.h"
@implementation HHNetworking

#pragma mark - GET请求,传入网址,参数,返回JSON数据与报错信息
+ (void)getRequestFromURL:(nonnull NSString *)url
             parameters:(nullable NSDictionary *)parameters
               returnData:(void (^)(id responseObject,NSError *error))returnBlock
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    [session GET:url parameters:nil headers:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        returnBlock(responseObject,nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        returnBlock(nil,error);
        
    }];
}

#pragma mark - POST请求,传入网址,参数,返回JSON数据与报错信息
+ (void)postRequestFromURL:(nonnull NSString *)url
              parameters:(nullable NSDictionary *)parameters
                returnData:(void (^)(id responseObject,NSError *error))returnBlock{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    [session POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        returnBlock(responseObject,nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        returnBlock(nil,error);
    }];
}

#pragma mark - POST请求,可设置Header信息,传入网址,参数,返回JSON数据与报错信息
+ (void)postRequestFromURL:(nonnull NSString *)url
                parameters:(nullable NSDictionary *)parameters
                   headers:(nullable NSDictionary *)headers
                returnData:(void (^)(id responseObject,NSError *error))returnBlock
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    // 设置默认请求类型为二进制
//    session.responseSerializer = [AFJSONResponseSerializer serializer];
//    session.requestSerializer = [AFJSONRequestSerializer serializer];
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];
    
    [session POST:url parameters:parameters headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        returnBlock(responseObject,nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        returnBlock(nil,error);

    }];

}

#pragma mark - POST请求,可设置Header信息,传入网址,参数,返回JSON数据与报错信息
+ (void)postURL:(nonnull NSString *)url
                parameters:(nullable NSDictionary *)parameters
                   headers:(nullable NSDictionary *)headers
                returnData:(void (^)(id responseObject,NSError *error))returnBlock
{
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    session.responseSerializer = [AFJSONResponseSerializer serializer];
    session.requestSerializer = [AFJSONRequestSerializer serializer];
    [session POST:url parameters:parameters headers:headers progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"进度 - uploadProgress -- %@ - %@",uploadProgress ,uploadProgress.localizedDescription);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

        returnBlock(responseObject,nil);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        returnBlock(nil,error);

    }];

}

#pragma mark - 图片上传
+ (void)imageUpURL:(nonnull NSString *)url
        parameters:(nullable NSDictionary *)parameters
        imageArray:(nonnull NSArray <NSData *> *)imageArray
              name:(nonnull NSString *)name
        fileNames:(nonnull NSArray <NSString *> *)fileNames
          mimeType:(nonnull NSString *)mimeType
        returnData:(void (^)(id responseObject,NSError *error))returnBlock
{
    // 获取AF Session Manager对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 设置默认请求类型为二进制
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   
    // manager.securityPolicy.allowInvalidCertificates = YES; //
    [manager POST:url parameters:parameters headers:nil  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i= 0 ; i< imageArray.count; i++) {
            
            [formData appendPartWithFileData:[imageArray objectAtIndex:i] name:name fileName:[fileNames objectAtIndex:i] mimeType:mimeType];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        returnBlock(responseObject,nil);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        returnBlock(nil,error);
        
    }];
}

#pragma mark - 单张图片上传
+ (void)imageUpURL:(nonnull NSString *)url
             image:(UIImage *)image
        parameters:(nullable NSDictionary *)parameters
           headers:(NSDictionary *)headersDic
        returnData:(void (^)(id responseObject,NSError *error))returnBlock
{
    // 获取AF Session Manager对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 设置默认请求类型为二进制
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    
    [manager POST:url parameters:parameters headers:headersDic   constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
//         NSLog(@"imageData - %@",imageData);
    
        NSData *imageData = UIImageJPEGRepresentation(image, 0.05);
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
        NSLog(@"fileName - %@",fileName);
        // 上传图片，以文件流的格式
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/png"];
    
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress -- %@ - %@",uploadProgress ,uploadProgress.localizedDescription);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求数据成功,回传数据
        NSLog(@"上传成功");
        returnBlock(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"流error - %@",error);
        // 请求数据错误,回传错误信息
        
        returnBlock(nil,error);
    }];

}

#pragma mark - 图片上传
+ (void)imageUpURL:(nonnull NSString *)url
           parameters:(nullable NSDictionary *)parameters
           imageArray:(nonnull NSArray *)imageArray
                 name:(nonnull NSString *)name
           fileNames:(nonnull NSArray *)fileNames
             mimeType:(nonnull NSString *)mimeType
              success:(void (^)(id responseObject))success
             progress:(nullable void (^)(NSProgress * _Nonnull))progress failure:(void(^_Nullable)(NSError * _Nullable error)) failure
{
    // 获取AF Session Manager对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 设置默认请求类型为二进制
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
   
    // manager.securityPolicy.allowInvalidCertificates = YES; //
    [manager POST:url parameters:parameters headers:nil  constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i= 0 ; i< imageArray.count; i++) {
            
            [formData appendPartWithFileData:[imageArray objectAtIndex:i] name:name fileName:[fileNames objectAtIndex:i] mimeType:mimeType];
        }
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {

        progress(uploadProgress);
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        success(responseObject);
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        failure(error);
        
    }];
}

+ (void)videoUpURL:(nonnull NSString *)url
        parameters:(nullable NSDictionary *)parameters
           headers:(nullable NSDictionary *)headerDic
          videoData:(nonnull NSData *)videoData
          name:(nonnull NSString *)name
          fileName:(nonnull NSString *)fileName
          mimeType:(nonnull NSString *)mimeType
           returnData:(void (^)(id responseObject,NSError *error))returnBlock
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 设置默认请求类型为二进制
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.requestSerializer =  [AFJSONRequestSerializer serializer];
    [manager POST:url parameters:parameters headers:headerDic constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:videoData name:name fileName:fileName mimeType:mimeType];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"上传进度 --- %@ -- %@",uploadProgress,uploadProgress.localizedDescription);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 请求数据成功,回传数据
        returnBlock(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"流error - %@",error);
        // 请求数据错误,回传错误信息
        returnBlock(nil,error);
    }];

}

#pragma mark - 通过body 传参 ，POST请求
+ (void)postWithUrl:(nonnull NSString *)url
               body:(nullable NSDictionary *)body
            success:(void(^)(NSDictionary *response))success
            failure:(void(^)(NSError *error))failure
{
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:body options:0 error:&error];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    //如果你不需要将通过body传 那就参数放入parameters里面
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:url parameters:nil error:nil];

    request.timeoutInterval= 10;

    // 设置header
//    [request setValue:@"" forHTTPHeaderField:@"token"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
   
    // 设置body 在这里将参数放入到body
    [request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];

    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/json",@"text/javascript",@"text/plain",nil];

    manager.responseSerializer = responseSerializer;

    [[manager dataTaskWithRequest:request uploadProgress:nil downloadProgress:nil completionHandler:^(NSURLResponse *response,id responseObject,NSError *error){

        if(responseObject!=nil){
            NSDictionary *itemDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            success(itemDic);
        }
        if (error) {
            failure(error);
        }

    }]resume];
}


/// POST 请求
/// @param url 网址
/// @param parameter 参数
/// @param isHud 是否设置蒙版
/// @param successBlock 成功返回
/// @param errorBlock 失败返回
+ (void)postRequestFromURL:(NSString *)url andParameter:(nullable id)parameter isHUD:(BOOL)isHud success:(HHRequestSuccestBlock)successBlock error:(HHRequestErrorBlock)errorBlock{
    // 请求队列管理者
    AFHTTPSessionManager * manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//  报400或者415  这种是需要将请求参数设为JSON格式(加这句解决）
    manager.requestSerializer =  [AFJSONRequestSerializer serializer];

    if (isHud) {
        [HHNetworking ShowHUD];
    }
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
    [manager POST:url parameters:parameter headers:nil progress:^(NSProgress * _Nonnull uploadProgress) {

    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [HHNetworking HiddenHUD];
//        NSLog(@"responseObject -- %@",responseObject);
        if ([responseObject[@"status"] intValue] == 200) {
            if (successBlock) {
                successBlock(task,responseObject,200);
            }
        }else if ([responseObject[@"status"] intValue] == 400) {
            // token失效
            [[NSNotificationCenter defaultCenter] postNotificationName:@"HHNetError" object:nil userInfo:nil];
        }else{
            [HHNetworking ShowHUDWithMsg:responseObject[@"msg"]?:responseObject[@"message"]];
            if (successBlock) {
                successBlock(task,responseObject,[responseObject[@"status"] intValue]);
            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"error -- %@",error);
        if (errorBlock) {
            errorBlock(task,error);
        }
        [HHNetworking HiddenHUD];
    }];
    
}

//显示挡板
+(void)ShowHUD{
   
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if ([HHNetworking getWindow]){
            [MBProgressHUD showHUDAddedTo:[HHNetworking getWindow] animated:YES];
        }
   });
   
}
//隐藏挡板
+(void)HiddenHUD
{
  
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       if ([HHNetworking getWindow])
       {
           [MBProgressHUD hideHUDForView:[HHNetworking getWindow] animated:YES];
       }
   });
}

+ (void)ShowHUDWithMsg:(NSString *)msg
{
   dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
       if ([HHNetworking getWindow]) {
//           MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[HHTool getKeyWindow] animated:YES];
//           hud.detailsLabel.text = msg;
//           hud.detailsLabel.font = [UIFont boldSystemFontOfSize:15];
//           [hud hideAnimated:YES afterDelay:1.5];
           [MBProgressHUD showSuccess:msg toView:[HHNetworking getWindow]];
       }
   });
}

#pragma mark - 获取Window，添加视图用
+ (UIWindow *)getWindow{
    if (@available(iOS 13.0, *)){
        for (UIWindowScene* windowScene in [UIApplication sharedApplication].connectedScenes) {
            if (windowScene.activationState == UISceneActivationStateForegroundActive)
            {
                for (UIWindow *window in windowScene.windows)
                {
                    if (window.isKeyWindow)
                    {
                        return window;
                        break;
                    }
                }
            }
        }
    }else{
        return [UIApplication sharedApplication].keyWindow;
    }
    return nil;
}
@end
